package com.result.demo.global.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.result.demo.global.annotation.ResponseResult;
import com.result.demo.global.enums.ResultCode;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.SortedMap;

/**
 * 拦截器  主要用来做请求校验 以及为控制层增加返回包装标识
 * @author chao.z
 */
public class ResponseResultInterceptor implements HandlerInterceptor {

    public static final String RESPONSE_RESULT_ANN = "RESPONSE-RESULT-ANN";

    /**
     * 此代码核心思想，就是获取此请求，是否需要返回值包装，设置一个属性标记。
     *
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {




        // 方法校验

        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();
            if (clazz.isAnnotationPresent(ResponseResult.class)) {
                request.setAttribute(RESPONSE_RESULT_ANN, clazz.getAnnotation(ResponseResult.class));
            } else if (method.isAnnotationPresent(ResponseResult.class)) {
                request.setAttribute(RESPONSE_RESULT_ANN, method.getAnnotation(ResponseResult.class));
            }
            return true;
        } else {
            return  initResponse(response, ResultCode.API_NOT_EXIST);
        }
    }


    private boolean initResponse(HttpServletResponse response,ResultCode resultCode) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", resultCode.getCode());
        jsonObject.put("message", resultCode.getMessage());
        jsonObject.put("data", null);
        writer.write(jsonObject.toString());
        return false;
    }


}
